package cn.dianhun.security.servie;

import cn.dianhun.security.pojo.TUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author
 * @create
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TUserEntity user = userService.getUserByUsername(s);
        System.out.println(user.toString());
        List<String> permissions = userService.findPermissionsByUserId(user.getId());
        String[] strings = new String[permissions.size()];
        permissions.toArray(strings);

//        ArrayList<GrantedAuthority> objects = new ArrayList<>();
//        objects.add(new SimpleGrantedAuthority("ROLE_VIP"));
//        System.out.println(strings.toString());

        // 设置权限和角色
        // 1. commaSeparatedStringToAuthorityList放入角色时需要加前缀ROLE_，而在controller使用时不需要加ROLE_前缀
        // 2. 放入的是权限时，不能加ROLE_前缀，hasAuthority与放入的权限名称对应即可
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("vip1,ROLE_VIP");
        UserDetails p = User
                .withUsername(user.getFullname()).password(user.getPassword())
                .authorities(grantedAuthorities)
                //.authorities((GrantedAuthority) permissions)
                .build();
        return p;
    }
}
